package com.foreknow.hospital.dao.impl;

import com.foreknow.hospital.dao.UsersDao;
import com.foreknow.hospital.po.Users;
import com.foreknow.hospital.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UsersDaoImpl implements UsersDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;

    @Override
    public int saveUsers(Users users) throws SQLException {
        int result = 0;
        String sql = "insert into users values(?,?,?,?,?,?,?,1)";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,users.getUserId());
            pst.setString(2,users.getPassword());
            pst.setString(3,users.getRealName());
            pst.setInt(4,users.getSex());
            pst.setString(5,users.getIdentityCard());
            pst.setString(6,users.getBirthday());
            pst.setInt(7,users.getUserType());
            result = pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public Users getUsersByUserIdByPass(String userId, String password) throws SQLException {
        Users users = null;
        String sql = "select * from users where userId = ? and password = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            ResultSet rs = pst.executeQuery();
            if(rs.next()){
                users = new Users();
                users.setUserId(rs.getString("userId"));
                users.setPassword(rs.getString("password"));
                users.setRealName(rs.getString("realName"));
                users.setSex(rs.getInt("Sex"));
                users.setIdentityCard(rs.getString("identityCard"));
                users.setBirthday(rs.getString("birthday"));
                users.setUserType(rs.getInt("userType"));
            }
        }finally {
            DBUtil.close(pst);
        }
        return users;
    }

    @Override
    public int getUsersById(String userId) throws SQLException {
        int count =  0;
        String sql = "select * from users where userId = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, userId);
            rs = pst.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1); //获取到结果集中的一列
            }
        }finally {
            DBUtil.close(pst);
        }
        return count;
    }
}
